<template>
  <div class="flex justify-between h-full overflow-hidden">
    <div class="h-full flex flex-col border-r" :class="isExpand ? 'w-[320px]' : 'w-[120px]'">
      <!-- <a-drawer :open="true" placement="left" :closable="false" :mask="false" :body-style="{ padding: 0 }" :get-container="false"> -->
      <BaseTitle :title="isExpand ? '病历文书' : ''" class="mb-4 mt-2 border-b">
        <div class="flex justify-between items-center">
          <a-button type="link" size="large" @click="getTreeData()">
            <RedoOutlined />
          </a-button>
          <a-button type="link" size="large" @click="isExpand = !isExpand">
            <MenuFoldOutlined v-if="isExpand" />
            <MenuUnfoldOutlined v-else />
          </a-button>
        </div>
      </BaseTitle>
      <TreeSelect ref="treeSelectRef" :source-data="treeData" :loading="treeLoading || emrLoading" @success="onSelectEmr" @refresh="getTreeData()" />
      <template v-if="isExpand">
        <a-divider class="w-full mb-2" />
        <div class="mb-4 flex justify-between">
          <a-button type="primary" class="flex-1 mr-2" @click="templateShow = true">新增</a-button>
          <a-button class="flex-1 mr-2" @click="onSubmitEmr(1, true)">批量提交</a-button>
        </div>
      </template>
    </div>
    <a-spin :spinning="emrLoading" tip="初始化中..." wrapper-class-name="h-full overflow-hidden flex-1 mt-2" class="">
      <div class="h-full flex flex-col pb-4">
        <div class="flex justify-between items-center">
          <div class="ml-2 font-bold">
            {{ currentEmrInfo.templateName }}
          </div>
          <div>
            <a-button :disabled="!isShowEmr || currentEmrInfo.status === '1'" type="primary" ghost class="mr-2" @click="onSaveEmr">保存</a-button>
            <a-button v-if="currentEmrInfo.status === '1'" :disabled="!isShowEmr" type="primary" class="mr-2" @click="onSubmitEmr(0)">撤销</a-button>
            <a-button v-else :disabled="!isShowEmr" type="primary" class="mr-2" @click="onSubmitEmr(1)">提交</a-button>
            <a-button :disabled="!isShowEmr" @click="onPrint">打印</a-button>
          </div>
        </div>
        <div class="border-t border-b py-2 mt-2">
          <EditModule :disabled="currentEmrInfo.status === '1'" @change-font-style="changeFontStyle" @change-font-sub-sup="onChangeFontSubSup" />
        </div>
        <div class="flex justify-center flex-1 overflow-hidden mx-auto">
          <div v-if="categroyType === '1'" class="w-28 mt-20 text-center text-base ml-8">
            <div class="mb-4 cursor-pointer" @click="disposeShow = true">处置</div>
            <a-divider />
            <div class="mb-4 cursor-pointer" @click="checkShow = true">检查</div>
            <a-divider />
            <div class="mb-4 cursor-pointer" @click="laboratoryShow = true">检验</div>
            <a-divider />
            <div class="mb-4 cursor-pointer" @click="westernShow = true">西成药</div>
            <a-divider />
            <div class="mb-4 cursor-pointer" @click="tcmShow = true">中草药</div>
            <a-divider />
            <div class="mb-4 cursor-pointer" @click="operationShow = true">手术</div>
            <a-divider />
            <div class="mb-4 cursor-pointer">常用语</div>
            <a-divider />
          </div>
          <div class="relative w-[820px]" :class="currentEmrInfo.status === '1' ? 'template-status' : ''">
            <div
              v-show="isShowEmr"
              id="myWriterControl"
              dctype="WriterControlForWASM"
              contentrendermode="NormalHtmlEditable"
              workspacebackcolorstring="#DEDEDE"
              useclassattribute="true"
              heightcompress="true"
              backgroundtextoutputmode="None"
              imagedataembedinhtml="true"
              HeaderFooterEditable="true"
              pixelpagespacing="5"
              clientcontextmenutype="Custom"
              usedcwriterminijs="True"
              showdebuginfo="false"
              registercodeindex="0"
            >
              正在加载...
            </div>
            <div v-show="!isShowEmr" class="h-full text-center mt-4 border">
              <a-empty />
            </div>
          </div>
        </div>
      </div>
    </a-spin>
  </div>
  <EmrTemplateModal v-model:open="templateShow" :current-patient="currentPatient" :categroy-type="categroyType" @success="onImportTemplateSuccess" />
  <TabDispose v-model:open="disposeShow" />
  <Western v-model:open="westernShow" />
  <Tcm v-model:open="tcmShow" />
  <Check v-model:open="checkShow" />
  <Laboratory v-model:open="laboratoryShow" />
  <Operation v-model:open="operationShow" />
</template>
<script setup>
import { message } from 'ant-design-vue'
import { MenuFoldOutlined, MenuUnfoldOutlined, RedoOutlined } from '@ant-design/icons-vue'
// import useAppStore from '../../store'
import EditModule from '@/views/emr/emr-template/components/EditModule.vue'
import EmrTemplateModal from './components/EmrTemplateModal'
import TreeSelect from './components/TreeSelect'
import TabDispose from './components/TabDispose'
import Western from './components/Western'
import Tcm from './components/Tcm'
import Check from './components/Check'
import Laboratory from './components/Laboratory'
import Operation from './components/Operation'

const props = defineProps({
  currentPatient: {
    type: Object,
    default: () => ({})
  },
  categroyType: {
    type: String,
    default: '1'
  }
})

const isExpand = ref(true)
const templateShow = ref(false)
// const store = useAppStore()
const state = reactive({
  ctl: null,
  props: {}
})
const disposeShow = ref(false)
const westernShow = ref(false)
const tcmShow = ref(false)
const treeLoading = ref(true)
const emrLoading = ref(true)
const checkShow = ref(false)
const laboratoryShow = ref(false)
const operationShow = ref(false)
// const tempId = ref('')
// const cateId = ref('')
const templateUrl = ref('')
const treeData = ref([])
const isShowEmr = ref(null)
const treeSelectRef = ref(null)
const getTreeData = async () => {
  treeLoading.value = true
  // treeData.value = []
  currentEmrInfo.value = {}
  const { code, data, msg } = await post('emr/emrCategory/getEmrCategoryTreeTempleteId', {
    categroyType: props.categroyType,
    brId: props.currentPatient.brId,
    jzbh: props.currentPatient.jzbh
  })
  treeLoading.value = false
  if (code !== 0) return message.error(msg)
  treeData.value = data
  currentEmrInfo.value = {}
  isShowEmr.value = false
}
// 电子病历
const loadScript = () => {
  return new Promise((resolve) => {
    const script = document.createElement('script')
    script.type = 'text/javascript'
    script.src = 'https://www.dcwriter.cn:8099/ServicePage.aspx?wasmres=dcwriter5.js'
    script.onload = () => resolve()
    document.head.insertBefore(script, null)
  })
}
const currentEmrInfo = ref({})
const onSelectEmr = (item) => {
  if (item) {
    currentEmrInfo.value = item
    getEmrXml(currentEmrInfo.value.id)
  } else {
    currentEmrInfo.value = {}
    isShowEmr.value = false
  }
}
const getEmrXml = async (id) => {
  const ctl = document.getElementById('myWriterControl')
  const { data, code, msg } = await post('/emr/patientEmrDocument/getPatientEmrDocument', {
    id
  })
  if (code !== 0) return message.error(msg)
  templateUrl.value = data
  if (data) {
    isShowEmr.value = true
  } else {
    isShowEmr.value = false
  }
  ctl.LoadDocumentFromString(data)
  state.ctl = ctl
  setTimeout(() => {
    addStatusDom()
  }, 300)
}

const onSaveEmr = async () => {
  const ctl = document.getElementById('myWriterControl')
  const resultToString = ctl.XMLTextForSave
  const { code, data, msg } = await post('/emr/patientEmrDocument/savePatientEmrDocument', {
    brId: props.currentPatient.brId,
    categroyId: currentEmrInfo.value.categroyId,
    id: currentEmrInfo.value.id,
    templateId: currentEmrInfo.value.templateId,
    xml: resultToString,
    lsh: props.currentPatient.inplsh,
    categroyType: props.categroyType
  })
  if (code !== 0) return message.error(msg)
  message.success('保存成功')
  getEmrXml(data.id)
}

const onSubmitEmr = async (type, isBatch = false) => {
  const { code, msg, data } = await post('/emr/emrDocumentFile/doChangeEmrTempleteAndCategoryStatus', {
    brId: props.currentPatient.brId,
    categroyType: props.categroyType,
    id: isBatch ? null : currentEmrInfo.value.id,
    categroyId: isBatch ? null : currentEmrInfo.value.categroyId,
    templateId: isBatch ? null : currentEmrInfo.value.templateId,
    status: type
  })
  if (code !== 0) return message.error(msg)
  message.success('操作成功')
  if (isBatch) {
    getTreeData()
  } else {
    await getTreeData()
    onSelectEmr(data?.[0])
    setTimeout(() => {
      treeSelectRef.value.setSelectedKeys(data[0]?.id)
    }, 100)
  }
}
const addStatusDom = () => {
  const dom = document.querySelector('.template-status div[dctype="page-container"]')
  //添加角标
  const span = document.createElement('span')
  span.style.position = 'absolute'
  span.style.width = '36px'
  span.style.height = '36px'
  span.style.top = '5px'
  span.style.right = '9px'
  span.style.backgroundImage =
    'url()'
  dom.appendChild(span)
}

const onImportTemplateSuccess = async (data) => {
  await getTreeData()
  getEmrXml(data.id)
  currentEmrInfo.value.categroyId = data.categoryId
  currentEmrInfo.value.templateId = data.templateId
  currentEmrInfo.value.id = data.id
  treeSelectRef.value.setSelectedKeys(data.id)
}
watch(
  () => props.currentPatient.brId,
  (val) => {
    if (val) {
      getTreeData()
      isShowEmr.value = false
    } else {
      treeData.value = []
      isShowEmr.value = false
      currentEmrInfo.value = {}
      treeLoading.value = false
    }
  }
)
const onPrint = () => {
  const ctl = document.getElementById('myWriterControl')
  ctl.PrintDocument()
}
const changeFontStyle = (e) => {
  if (state.ctl) state.ctl.setFontObject(e)
}
const onChangeFontSubSup = (e) => {
  if (state.ctl) state.ctl.DCExecuteCommand(e.name, e.val, e.memo)
}
onMounted(async () => {
  await loadScript()
  props.currentPatient.brId ? getTreeData() : (treeLoading.value = false)
  const ctl = document.getElementById('myWriterControl')
  if (window.CreateWriterControlForWASM) {
    window.CreateWriterControlForWASM(ctl)
  }
  window.WriterControl_OnLoad = () => {
    emrLoading.value = false
  }
})
</script>
<style lang="less" scoped>
:deep(.ant-spin-container) {
  height: 100%;
}
// .template-status {
//   &::after {
//     position: absolute;
//     top: -17px;
//     left: 12px;
//     background-image: url('');
//   }
// }
</style>
